<?php

class Mojito_Config_Json extends Zend_Config
{
	/**
     * Create Zend_Config object from json formatted file
     *
     * @param	string $file
     * @param	string [$section=null]
     * @param	array [$options=array()]
     */

	public function __construct($file,$section=null,$options=array())
	{
		if (!file_exists($file)) throw new Zend_Config_Exception($file.' could not be found.');
		else
		{			
			$jsonString = file_get_contents($file);
			$dataArray = Zend_Json::decode($jsonString);
			
			if ($dataArray==null) throw new Zend_Config_Exception($file.' is not formatted correctly.');
			
			// figure out inheritance
			foreach ($dataArray as $key => &$val)
			{
				if (isset($val['_inherits']))
				{
					if (!isset($dataArray[$val['_inherits']])) throw new Zend_Config_Exception('Section '.$key.' could not find section '.$val['_inherits'].' from which to inherit.');
					else $val=array_merge_recursive($dataArray[$val['_inherits']],$val);
					unset($val['_inherits']);
				}
			}
			
			// determine section to return
			if (!empty($section))
			{
				if (!array_key_exists($section,$dataArray)) throw new Zend_Config_Exception($section.' was not found in '.$file);
				else $dataArray = $dataArray[$section];
			}
			
			$allowModifications = isset($options['allowModifications'])?(bool) $options['allowModifications']:false;
			
			parent::__construct($dataArray, $allowModifications);
		}
	}
}